package com.lagou.edu.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import static  com.lagou.edu.config.IConstant.*;

/**
 * @author xh
 * @createTime 2020年10月26日 11:31.
 */
@Configuration
public class RabbitConfig {
    @Bean
    public Queue queue() {
        Map<String, Object> props = new HashMap<>();
        // 消息的生存时间 15s
        props.put("x-message-ttl", 15000);
        // 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加入死信队列）
        props.put("x-dead-letter-exchange", change_name_dlx);
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原队列的routingKey
        props.put("x-dead-letter-routing-key", routing_Key_dlx);
        Queue queue = new Queue(queue_name, true, false, false, props);
        return queue;
    }

    @Bean
    public Queue queueDlx() {
        Queue queue = new Queue(queue_name_dlx, true, false, false);
        return queue;
    }

    @Bean
    public Exchange exchange() {
        DirectExchange exchange = new DirectExchange(change_name, true,
                false, null);
        return exchange;
    }

    /**
     * 死信交换器
     *
     * @return
     */
    @Bean
    public Exchange exchangeDlx() {
        return new DirectExchange(change_name_dlx,
                true, false, null);
    }

    /**
     * 正常交换器与正常队列绑定
     * @return
     */
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with(routing_Key).noargs();
    }

    /**
     * 死信交换器绑定死信队列
     *
     * @return
     */
    @Bean
    public Binding bindingDlx() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with(routing_Key_dlx).noargs();
    }
}
